<?php
namespace app\share\controller;

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use think\Exception;
use think\facade\Request;

class Queue
{
    private $host = '139.196.186.154';
    private $port = '5672';
    private $user = 'admin';
    private $pwd = 'admin123456@';
    public function __construct()
{
    #建立一个到RabbitMQ服务器的连接
    $this->connection  = new AMQPStreamConnection($this->host,$this->port,$this->user,$this->pwd);
    $this->channel = $this->connection->channel();

}
    public function get()
    {
        $this->channel->queue_declare('task_queue', false, false, false, false);

        echo ' [*] Waiting for messages. To exit press CTRL+C', "\n";

        $callback = function($msg){
            echo " [x] Received ", $msg->body, "\n";
            sleep(substr_count($msg->body, '.'));
            echo " [x] Done", "\n";
            $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);

        };

        $this->channel->basic_qos(null, 1, null);
        $this->channel->basic_consume('task_queue', '', false, false, false, false, $callback);

        while(count($this->channel->callbacks)) {
            $this->channel->wait();
        }

        $this->channel->close();
        $this->connection->close();


    }

    public function send()
    {
        $params = Request::param();
        $msg1 = $params['msg'];

        $msg = new AMQPMessage($msg1,array('delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT)); # #使消息持久化
        $this->channel->basic_publish($msg, '', 'task_queue');

        echo " [x] Sent ,".$msg1 . "\n";
        $this->channel->close();
        $this->connection->close();
    }



}